package com.ccy.legendary.socker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/manage/{userCode}")
@Component
public class WebSocketManage {

    private WSMessageService wsMessageService = (WSMessageService) ApplicationContextRegister.getApplicationContext().getBean("wSMessageService");

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //在线人数
    private static AtomicInteger onlineCount = new AtomicInteger();

    //存放每个客户端对应的WebSocketServer对象。
    static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 调用成功
     * @param session 当前用户会话
     * @param userCode 当前用户Code
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userCode") String userCode){
        sessionPools.put(userCode, session);
        onlineCount.incrementAndGet();
        StringBuilder sb = new StringBuilder();
        sb.append(userCode).append("加入游戏！当前人数为").append(onlineCount);
        logger.info(sb.toString());
        try {
            wsMessageService.sendAll(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "userCode") String userCode){
        sessionPools.remove(userCode);
        onlineCount.decrementAndGet();
        System.out.println(userCode + "断开连接！当前人数为" + onlineCount);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message){
        logger.info(message);
        try {
            wsMessageService.sendAll(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        logger.error(session+"连接发生错误");
        throwable.printStackTrace();
    }

}
